import cv2
import serial

# 初始化串口
ser = None
try:
    ser = serial.Serial(
        port='/dev/ttyAMA0',
        baudrate=115200,
        timeout=1
    )
    if ser:
        print("串口已连接")
    else:
        print("警告：串口连接失败")
except:
    print("警告：无法连接串口，将继续运行但不发送数据")

# 初始化摄像头
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)

# 检测最大矩形并返回四个角点
def detect_largest_rectangle(img):
    # 转换到HSV色彩空间
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    
    # 定义红色范围 (扩大范围提高灵敏度)
    lower_red1 = (0, 50, 50)
    upper_red1 = (15, 255, 255)
    lower_red2 = (150, 50, 50)
    upper_red2 = (180, 255, 255)
    
    # 创建红色掩膜并增强
    mask1 = cv2.inRange(hsv, lower_red1, upper_red1)
    mask2 = cv2.inRange(hsv, lower_red2, upper_red2)
    red_mask = cv2.bitwise_or(mask1, mask2)
    
    # 形态学操作增强红色区域
    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))
    red_mask = cv2.morphologyEx(red_mask, cv2.MORPH_CLOSE, kernel)
    red_mask = cv2.morphologyEx(red_mask, cv2.MORPH_OPEN, kernel)
    
    # 应用颜色过滤
    filtered = cv2.bitwise_and(img, img, mask=red_mask)
    
    gray = cv2.cvtColor(filtered, cv2.COLOR_BGR2GRAY)
    blurred = cv2.GaussianBlur(gray, (5, 5), 0)
    edges = cv2.Canny(blurred, 30, 100)
    
    contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    rectangles = []
    
    for cnt in contours:
        peri = cv2.arcLength(cnt, True)
        approx = cv2.approxPolyDP(cnt, 0.02 * peri, True)
        
        if len(approx) == 4:
            rectangles.append(approx)
    
    if rectangles:
        largest = max(rectangles, key=cv2.contourArea)
        return largest.reshape(4, 2)
    return None

# 主循环
while True:
    ret, frame = cap.read()
    if not ret:
        print("无法获取摄像头画面")
        break
    
    # 显示HSV值用于调试
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    x, y = 10, 30
    cv2.putText(frame, f"H: {hsv[y,x][0]}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255,255,255), 2)
    cv2.putText(frame, f"S: {hsv[y,x][1]}", (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255,255,255), 2)
    cv2.putText(frame, f"V: {hsv[y,x][2]}", (10, 90), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255,255,255), 2)

    # 检测最大矩形
    corners = detect_largest_rectangle(frame)
    if corners is not None:
        # 绘制矩形并标注ABCD
        cv2.drawContours(frame, [corners.astype(int)], -1, (0, 255, 0), 2)
        
        # 按顺时针顺序标注ABCD
        labels = ['A', 'B', 'C', 'D']
        for i, (x, y) in enumerate(corners.astype(int)):
            cv2.putText(frame, labels[i], (x, y), cv2.FONT_HERSHEY_SIMPLEX, 
                        0.8, (0, 0, 255), 2)
        
        # 发送带ABCD标识的坐标数据
        if ser and ser.is_open:
            coord_str = ",".join([f"{label}:{x},{y}" for label, (x,y) in zip(labels, corners)])
            ser.write(f"RECT:{coord_str}\n".encode('utf-8'))
    
    # 显示画面和红色掩膜
    cv2.imshow('Rectangle Detection', frame)
    
    # 按q退出
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# 释放资源
cap.release()
cv2.destroyAllWindows()
if ser and ser.is_open:
    ser.close()
